package com.cms.interceptor;

import com.cms.common.model.services.AdminUserService;
import com.cms.html.HtmlRenderService;
import com.cms.common.model.entity.AdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Copyright (c) Since 2024 ThinkCms - All Rights Reserved
 *
 * @author what
 * @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * @Date 2024/10/31 11:09
 */

@Component
@Order(2)
public class WebInterceptor extends BaseAuthInterceptor {

    String sessionKey = "web_login_token";

    @Autowired
    HtmlRenderService htmlRenderService;
    @Autowired
    AdminUserService adminUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isLogin = adminUserService.checkLogin(request, response);
        if (!isLogin) {
            response.sendRedirect("/admin/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            HttpSession session = request.getSession();
            String token = (String) session.getAttribute(sessionKey);
            if (token != null) {
                String[] tokens = token.split("|");
                Long time = Long.parseLong(tokens[0]);
                if ((time + 1000 * 60 * 60 * 3) < System.currentTimeMillis()) {//登录状态超过3小时没使用自动下线
                    AdminUser adminUser = (AdminUser) session.getAttribute(token);
                    if (adminUser != null) {
                        modelAndView.getModel().put("role", adminUser.getRoles());
                    }
                }

            }
            modelAndView.getModel().put("menu_active", request.getRequestURI());
        }


    }

}
